package com.example.hbutliving.util;

import com.example.hbutliving.config.redis.RedisKey;
import com.example.hbutliving.exception.ParamErrorException;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author lizijian
 */
@Component
public class RedisUtil {


  public static RedisTemplate<String,String> stringRedisTemplate;

  @Autowired
  public void setStringRedisTemplate(
      StringRedisTemplate stringRedisTemplate) {
    RedisUtil.stringRedisTemplate = stringRedisTemplate;
  }

  /**
   * 获取指定id用户在线状态
   * @param userId
   * @return
   */
  public static boolean getOnlineState(int userId){
    return stringRedisTemplate.opsForValue().get(RedisKey.ONLINE+userId)!=null;
  }

  /**
   * 存储注册邮箱验证码
   */
  public static void setEmailCode(String code,String value){
    stringRedisTemplate.opsForValue().set(RedisKey.EMAIL_CODE+code,value,300L, TimeUnit.SECONDS);
  }

  public static void verifyEmailCode(String email,String emailCode) throws ParamErrorException {
    String redisEmail = stringRedisTemplate.opsForValue().get(RedisKey.EMAIL_CODE + emailCode);
    if(redisEmail==null||!redisEmail.equals(email)){
      throw new ParamErrorException("验证码错误");
    }
  }
}
